#include "SFC_Inc.hpp"
#include "Setup.h"
#include "SFC_Label.h"

SFC_Label::SFC_Label()
{
	TextChanged.Bind(Text);
	ColorChanged.Bind(Color);
	TransformChanged.Bind(Transform);
	TextChanged += {this, &SFC_Label::SetDurty};
	ColorChanged += {this, &SFC_Label::SetDurty};
	TransformChanged += {this, &SFC_Label::SetDurty};
	LoadRes();
}

void SFC_Label::LoadRes()
{
	this->font = CreateFontHandle(DEFAULT_FONT, 16);
	// Create cache surface
	if (this->Cache != nullptr)
		FreeSurface(this->Cache);
	this->Cache = CreateSurface(this->Size.w, this->Size.h);
	FillRect(this->Cache, nullptr, 0x00000000);
}

void SFC_Label::EventRouter(SFC_Event &Event)
{
	if (Event.Type == EventType::Window && Event.Window.Type == WindowEventType::Paint)
	{
		Paint();
	}
}

void SFC_Label::Paint()
{
	if (this->Durty == false) return ;

	LoadRes();
	if (this->Transform == false) {
		// Draw background surface
		FillRect(this->Cache, nullptr, this->Color | 0xFF000000);
	}
	// Draw frontground surface
	Surface TextSurface = RenderText(this->font, this->Text.c_str(), this->FrontColor);

	SFC_Rect DisplayRect = {this->Size.x, this->Size.y, TextSurface->w, TextSurface->h};
	if (this->HCenter == true)
		DisplayRect.x += (this->Size.w - TextSurface->w) / 2;
	if (this->VCenter == true)
		DisplayRect.y += (this->Size.h - TextSurface->h) / 2;
	BlitSurface(TextSurface, nullptr, this->Cache, &DisplayRect);
	FreeSurface(TextSurface);
	this->Durty = false;
}